package com.bbs.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.bbs.entity.Moderator;
import com.bbs.util.DBHelp;
import com.bbs.util.RowMapper;

public class ModeratorDao {
	private DBHelp<Moderator> db = new DBHelp<Moderator>();
	
	public List<Moderator> findModeratorsByUid(int uid){
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT m.id,m.createdate,t_user_id,t_blocks_id,b.id AS blocksid,b.name,b.pid,b.content FROM t_moderator AS m ");
		sql.append("LEFT JOIN t_blocks AS b ");
		sql.append("ON t_blocks_id = b.id WHERE t_user_id = ?");
		
		return db.queryForList(sql.toString(), new ModeratorMapper(), uid);
	}

	public int setModerator(String now, int uid, int bid) {
		String sql = "INSERT INTO t_moderator(createdate,t_user_id,t_blocks_id) VALUES(?,?,?)";
		return db.update(sql, now,uid,bid); 
	}

	public int delete(int uid, int bid) {
		String sql = "DELETE FROM t_moderator WHERE t_user_id = ? AND t_blocks_id = ?";
		return db.update(sql, uid,bid);
	}

	public List<Moderator> findByBid(int bid) {
		String sql = "SELECT m.id,m.createdate,t_user_id,t_blocks_id FROM t_moderator AS m WHERE t_blocks_id = ?";
		return db.queryForList(sql, new ModeratorMapper(), bid);
	}

	public void deleteBybid(int bid) {
		String sql = "DELETE FROM t_moderator WHERE t_blocks_id = ?";
		db.update(sql, bid);
	}

	public List<Integer> findModeratorsBybid(int bid) {
		String sql = "SELECT id,t_user_id,t_blocks_id FROM t_moderator WHERE t_blocks_id = ?";
		return new DBHelp<Integer>().queryForList(sql, new RowMapper<Integer>(){

			public Integer maprow(ResultSet rs) throws SQLException {
				return rs.getInt("t_user_id");
			}
		}, bid);
	}

	public Moderator findByUid(int id) {
		String sql = "SELECT m.id,m.createdate,t_user_id,t_blocks_id FROM t_moderator AS m WHERE t_user_id = ?";
		return db.queryForObject(sql, new ModeratorMapper(), id);
	}
}

class ModeratorMapper implements RowMapper<Moderator>{

	public Moderator maprow(ResultSet rs) throws SQLException {
		Moderator m = new Moderator();
		m.setId(rs.getInt("id"));
		m.setCreatedate(rs.getString("createdate"));
		m.setBlocks(new BlocksDao().findById(rs.getInt("t_blocks_id")));
		m.setUser(new Userdao().findById(rs.getInt("t_user_id")));
		return m;
	}
	
}
